<?php

namespace App\Http\Controllers;

use App\Http\Requests\WxAuthorizationsRequest;
use App\Models\User;
use Illuminate\Http\Request;

/**
 * 构建微信授权
 * Class AuthorizationsController
 * @package App\Http\Controllers
 */
class WxAuthorizationsController extends Controller
{
    /**
     * 获取用户登入信息
     * @param Request $request
     */
    public  function socialStore(WxAuthorizationsRequest $request) {
        $miniProgram = \EasyWeChat::miniProgram();
        $code=$request->input('code');
        $response=$miniProgram->auth->session($code);
        if (array_key_exists('errcode',$response)) {
           return response()->json(['msg'=>'code不正确请检查后再试']);
        }
        //判断用户是否存在
        $user=User::where('open_id',$response['openid'])->first();
        if (!$user) {
            //用户不存在创建用户
            $user=User::create([
                'name'=>$request->input('name'),
                'avatar'=>$request->input('avatar'),
                'open_id'=>$response['openid']
            ]);

        }
        //创建jwt
        $jwt=\Auth::guard('api')->login($user);
        return response()->json([
            'access_token' => $jwt,
            'token_type' => 'Bearer',
            'expires_in' => \Auth::guard('api')->factory()->getTTL() * 60
        ])->setStatusCode(201);
    }
}
